<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-10-25
 * Time: 03:01
 */

namespace app\api\controller;
use app\common\controller\ApiController;
use think\Db;
class Household extends ApiController
{
    function __construct(){
        parent::__construct();
    }

    // 获取房屋列表
    public function getList() {
        $param = $this->request->param();
        $where[] = ['u.status','=',$param['status']];
        if (@$param['gj_name']) {
            $param['search'] = $param['gj_name'];
        }
        if($param['status'] != 4){
            if(!empty($param['search'])) $where[] = ['u.name|u.phone|u.card_numbers|h.name','like','%' .$param['search']. '%'];
        }else{
            if(!empty($param['search'])) $where[] = ['name|phone','like','%' .$param['search']. '%'];
        }
        if (@$param['bd_id']) {
            $where[] = ['u.bd_info_id','=',$param['bd_id']];
        }
        if (@$param['user_type_val']) {
            $where[] = ['u.type','=',$param['user_type_val']];
        }
        if (@$param['log_val'] == 1) {
            $where[] = ['u.login_num','>',0];
        } elseif (@$param['log_val'] == 2) {
            $where[] = ['u.login_num','=',0];
        }
        if (@$param['lab_val']) {
            $where[] = ['u.labels_id','=',$param['lab_val']];
        }
        if (@$param['search'] && strlen(@$param['search']) > 2) {
            $hid = Db::name('wy_houses')->where('name','like','%' .@$param['search']. '%')->where('is_deleted','=',0)->column('id');
            if ($hid) {
                $or = Db::name('wy_houses_user_middle')->where('middle_type','=',1)->where('houses_id','in',implode(',',$hid))->column('house_user_id');
                if ($or) {
                    unset($where);
                    $where[] = ['u.status','=',$param['status']];
                    $where[] = ['u.id','in',implode(',',$or)];
                }
            }
        }
        if(!empty($this->userinfo['cm_message_id'])){
            if (@$param['cm_message_id']) {
                $where[] = ['u.bd_info_id','in',$param['cm_message_id']];
            } else {
                if($param['status']!=4){
                    $where[] = ['u.bd_info_id','in',$this->userinfo['cm_message_id']];
                }
                
            }
        }
        if($param['status'] != 4){
            $list = Db::name('wy_house_user u')
                ->join('wy_bd_info bd','u.bd_info_id = bd.id')
                ->join('wy_building b','u.building_id = b.id')
                ->join('wy_unit un','u.unit_id = un.id')
                ->join('wy_houses h','u.houses_id = h.id')
                ->where($where)
                ->where('h.is_deleted','=',0)
                ->field('u.*,bd.name bd_info_name,b.name building_name,un.name unit_name,h.name houses_name')
                ->page($param['pageNo'],$param['pageSize'])
                ->order('u.id','desc')->select();
            $count = Db::name('wy_house_user u')
                ->join('wy_bd_info bd','u.bd_info_id = bd.id')
                ->join('wy_building b','u.building_id = b.id')
                ->join('wy_unit un','u.unit_id = un.id')
                ->join('wy_houses h','u.houses_id = h.id')
                ->where($where)->where('h.is_deleted','=',0)->count();
            foreach ($list as $key=>$value){
                $list[$key]['uniKey']=$value['id'].'-'.$value['houses_id'];
                $list[$key]['type_text'] = '';
                $mideids=Db::name('wy_houses_user_middle')->alias('m')
                ->join('wy_house_user u','u.id = m.house_user_id')
                ->join('wy_houses h','m.houses_id = h.id')
                ->join('wy_bd_info bd','h.bd_info_id = bd.id')
                ->join('wy_building b','h.building_id = b.id')
                ->join('wy_unit un','h.unit_id = un.id')
                ->where('h.is_deleted','=',0)
                ->where('m.houses_id','<>',$value['houses_id'])
                ->where(['m.house_user_id'=>$value['id'],'m.middle_type'=>1])
                ->field('u.*,bd.name bd_info_name,b.name building_name,un.name unit_name,h.name houses_name,h.id as houses_ids')
                ->order('u.id','desc')->select();
                foreach($mideids as $ks=>$vs){
                    $mideids[$ks]['uniKey']=$vs['id'].'-'.$vs['houses_ids'];
                    unset($mideids[$ks]['phone']);
                    unset($mideids[$ks]['name']);
                }
                if($mideids){
                    $list[$key]['children']=$mideids;
                }
                
            }
        }else{
            $list = Db::name('wy_house_user u')->where($where)->field('u.*')->page($param['pageNo'],$param['pageSize'])->order('u.id','desc')->select();
            $count = Db::name('wy_house_user u')->where($where)->count();
        }
        foreach ($list as $key=>$value) {
            $list[$key]['gender'] = ['0'=>'未知','1'=>'男','2'=>'女','3'=>'其它'][$value['gender']];
        }
        return __success('ok',['data'=>$list,'pageSize'=>$param['pageSize'],'pageNo'=>$param['pageNo'],'totalCount'=>$count,'totalPage'=>ceil($count / $param['pageSize'])]);
    }

    // 添加or编辑住户
    public function operation() {
        $param = $this->request->param();
        unset($param['token']);
        if(empty($param['name'])) return __error('姓名不可为空');
        if(empty($param['phone'])) return __error('手机号不可为空');
        if($param['status'] != 4){
            if(empty($param['bd_building_unit_houses'])) return __error('所属小区/楼宇/单元/房屋不可为空');
            if(empty($param['type'])) return __error('住户身份不可为空');
            list($bd_info_id,$building_id,$unit_id,$houses_id) = $param['bd_building_unit_houses'];
            $param['bd_info_id'] = $bd_info_id;
            $param['building_id'] = $building_id;
            $param['unit_id'] = $unit_id;
            $param['houses_id'] = $houses_id;
            if(!empty($param['account_address'])) $param['account_address'] = implode(',',$param['account_address']);

        }
        if($param['id'] == 0){
            $id = Db::name('wy_house_user')->strict(false)->insert($param,true,true);
            if($param['status'] != 4){
                Db::name('wy_houses_user_middle')->insert(['houses_id'=>$houses_id,'house_user_id'=>$id,'long'=>1,'middle_type'=>1]);
            }
            return __success('添加成功',$id);
        }else{
            unset($param['bd_building_unit_houses']);
            $upRes = Db::name('wy_house_user')->update($param);
            return $upRes !== false ? __success('保存成功',$param['id']) : __error('保存失败');
        }
    }
    public function get_type(){
        $arr = ['0'=>'请选择','1'=>'买房迁入','2'=>'租房迁入','3'=>'亲属迁入','4'=>'卖房迁出','5'=>'租房到期迁出'];
        return __success('ok',['data'=>$arr]);
    }
    // 迁出住户
    public function moveOut() {
        $ids = $this->request->param('ids');
        $type = (int)$this->request->param('type');
        $bz = htmlspecialchars($this->request->param('bz'));
        $srr['type'] = $type;
        $srr['note'] = $bz;
        if(empty($ids)) return __error('参数错误');
        foreach($ids as $k=>$v){
            $parm=explode('-',$v);
            $reg = Db::name('wy_house_user')->where('id',$parm[0])->value('registry_text');
            if ($reg == 'excel') {
                $srr['note'] .= '由excel导入';
            }
            $srr['house_user_id'] = (int)$parm[0];
            $srr['houses_id'] = (int)$parm[1];
            $srr['create_time'] = date('Y-m-d H:i:s');
            Db::name('wy_houses_user_middle')->where('house_user_id',$parm[0])->where('houses_id',$parm[1])->delete();
            Db::name('wy_houses_user_note')->insert($srr);
            $upRes = Db::name('wy_house_user')->where('id',$parm[0])->where('houses_id',$parm[1])->update(['bd_info_id'=>0,'building_id'=>0,'unit_id'=>0,'houses_id'=>0,'status'=>4]);
        } 
        return  __success('迁出成功');
    }

    // 删除非住户
    public function delNon() {
        $ids = $this->request->param('ids');
        if(empty($ids)) return __error('参数错误');
        $delRes = Db::name('wy_house_user')->where('id','in',$ids)->delete();
        return !empty($delRes) ? __success('删除成功') : __error('删除失败');
    }

    // 获取住户信息
    public function getInfo() {
        $id = $this->request->param('id');
        if(empty($id)) return __error('参数错误');
        $info = Db::name('wy_house_user u')
            ->leftJoin('wy_bd_info bd','u.bd_info_id = bd.id')
            ->where('u.id',$id)->field('u.*,bd.name bd_name')->find();
        if (!empty($info['license'])) {
            $info['license'] = substr_replace($info['license'],"****",6,8);
        }
        $info['type_text'] = $this->getTypeText($info['type']);
        $info['createtime'] = empty($info['createtime']) ? '' : date('Y-m-d',strtotime($info['createtime']));
        $info['in_time'] = empty($info['in_time']) ? '' : date('Y-m-d',strtotime($info['in_time']));
        $info['pet_card_text'] = @$info['pet_card']?['0'=>'否','1'=>'是'][$info['pet_card']]:'';
        if(!empty($info['account_address'])) $info['account_address'] = explode(',',$info['account_address']);
        if(!empty($info['imgs'])) {
            $where = ['id'=>$info['imgs']];
            $info['imgs'] = model('wy_imgs')->getImgsList($where);
        }else $info['imgs'] = [];
        if(!empty($info['license_img'])) {
            $where = ['id'=>$info['license_img']];
            $info['license_img'] = model('wy_imgs')->getImgsList($where);
        }else $info['license_img'] = [];
        // 标签信息
        $labelsInfo = Db::name('wy_labels_middle')->alias('m')
            ->join('wy_labels l','m.labels_id = l.id')
            ->group('m.labels_id')
            ->where(['m.house_user_id'=>$id])->column('l.name');
        if(!empty($labelsInfo)) $info['labels_name'] = implode(',',$labelsInfo);
        // 相关房屋
        $houses = Db::name('wy_houses_user_middle')->alias('m')
            ->join('wy_houses h','m.houses_id = h.id')
            ->join('wy_bd_info bd','h.bd_info_id = bd.id')
            ->leftJoin('wy_labels l','h.labels = l.id')
            ->where(['m.house_user_id'=>$id,'m.middle_type'=>1])
            ->field('m.id,m.houses_id,m.house_user_id,h.name houses_name,bd.name bd_name,h.houses_type,m.type,m.time,m.long,l.name label_name')
            ->select();
        foreach ($houses as $key=>$item){
            $houses[$key]['houses_type_text'] = $this->getHouseTypeText($item['houses_type']);
            $houses[$key]['type_text'] = $this->getTypeText($item['type']);
            $houses[$key]['time_text'] = $item['long'] == 1 ? '长期' : date('Y-m-d',strtotime($item['time']));
        }
        // 相关车位
        $carArea = Db::name('wy_houses_user_middle')->alias('m')
            ->join('wy_car_area c','m.car_area_id = c.id')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->leftJoin('wy_labels l','c.labels_id = l.id')
            ->where(['m.house_user_id'=>$id,'m.middle_type'=>2])
            ->field('m.id,m.house_user_id,m.car_area_id,c.name car_area_name,bd.name bd_name,l.name label_name')
            ->select();
        // 相关车辆
        $car = Db::name('wy_houses_user_middle')->alias('m')
            ->join('wy_car c','m.car_id = c.id')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->leftJoin('wy_labels l','c.labels_id = l.id')
            ->where(['m.house_user_id'=>$id,'m.middle_type'=>3])
            ->field('m.id,m.house_user_id,m.car_id,c.name car_name,bd.name bd_name,c.username,c.phone,l.name label_name')
            ->select();
        return __success('ok',['data'=>$info,'houses'=>$houses,'car_area'=>$carArea,'car'=>$car]);
    }
    public function get_his(){
        $id = $this->request->param('id');
        if(empty($id)) return __error('参数错误');
        $list = Db::name('wy_houses_user_note')->where('house_user_id',$id)->select();
        $it = ['无','买房迁入','租房迁入','亲属迁入','卖房迁出','租房到期迁出'];
        foreach ($list as $k=>$v) {
            $house = Db::name('wy_houses')->where('id','=',$v['houses_id'])->field('bd_info_id,building_id,unit_id,name')->find();
            $list[$k]['name'] = $house['name'];
            $list[$k]['bd_name'] = Db::name('wy_bd_info')->where('id','=',$house['bd_info_id'])->value('name');
            $list[$k]['build_name'] = Db::name('wy_building')->where('id','=',$house['building_id'])->value('name');
            $list[$k]['unit_name'] = Db::name('wy_unit')->where('id','=',$house['unit_id'])->value('name');
            $list[$k]['type_txt'] = $it[$v['type']];
        }
        return __success('ok',['data'=>$list]);
    }
    public function get_price(){
        $id = $this->request->param('id');
        $houses_id = Db::name('wy_houses_user_middle')->where('house_user_id','=',$id)->where('houses_id','>',0)->column('houses_id') ?: [];
        $car_id = Db::name('wy_houses_user_middle')->where('house_user_id','=',$id)->where('car_id','>',0)->column('car_id') ?:[];
        $car_area_id = Db::name('wy_houses_user_middle')->where('house_user_id','=',$id)->where('car_area_id','>',0)->column('car_area_id') ?:[];
        $page = $this->request->get('pageNo','1');
        $pageSize = $this->request->get('pageSize','10');
        $models = model('no_pay');
        $data = $models->getList2($page,$houses_id,$car_id,$car_area_id,$pageSize);
        foreach ($data['data'] as $k=>$v) {
            if ($v['pay_status'] == 1) {
                $data['data'][$k]['status_txt'] = '已缴费';
            } else {
                $data['data'][$k]['status_txt'] = '未缴费';
            }
            if ($v['house_id'] > 0) {
                $data['data'][$k]['info'] = '房屋:';
            } elseif ($v['car_area_id'] > 0) {
                $data['data'][$k]['info'] = '车位:';
            } elseif ($v['car_id'] > 0) {
                $data['data'][$k]['info'] = '车辆:';
            } else {
                $data['data'][$k]['info'] = '';
            }
            $data['data'][$k]['label'] = '还没有标签';
            if($v['house_id'] > 0) {
                $hs = Db::name('wy_houses')->where('id', $v['house_id'])->field('building_id,unit_id,name,labels')->find();
                $bd = Db::name('wy_building')->where('id', $hs['building_id'])->value('name') ?: '';
                $ut = Db::name('wy_unit')->where('id', $hs['unit_id'])->value('name') ?: '';
                $data['data'][$k]['info'] = $data['data'][$k]['info'].$bd.'|'.$ut.'|'.$hs['name'];
                $data['data'][$k]['label'] = Db::name('wy_labels')->where('id',$hs['labels'])->value('name') ?: '还没有标签';
            }
            if($v['car_area_id'] > 0) {
                $car_area_det = Db::name('wy_car_area')->where('id', $v['car_area_id'])->field('name,labels_id')->find();
                $car_area_name = $car_area_det['name'];
                $data['data'][$k]['info'] = $data['data'][$k]['info'].' '.$car_area_name;
                $data['data'][$k]['label'] = Db::name('wy_labels')->where('id',$car_area_det['labels_id'])->value('name') ?: '还没有标签';
            }
            if($v['car_id'] > 0) {
                $car_det = Db::name('wy_car')->where('id', $v['car_id'])->field('name,labels_id')->find();
                $car_name = $car_det['name'];
                $data['data'][$k]['info'] = $data['data'][$k]['info'].' '.$car_name;
                $data['data'][$k]['label'] = Db::name('wy_labels')->where('id',$car_det['labels_id'])->value('name') ?: '还没有标签';
            }
        }
        if(empty($data['data'])) {
            return __error('暂无数据');
        } else {
            return __success('查询成功',  $data);
        }
        if(empty($id)) return __error('参数错误');
        $list = Db::name('wy_no_payment')->where('house_user_id',$id)->select();
        $it = ['无','买房迁入','租房迁入','亲属迁入','卖房迁出','租房到期迁出'];
        foreach ($list as $k=>$v) {
            $house = Db::name('wy_houses')->where('id','=',$v['houses_id'])->field('bd_info_id,building_id,unit_id,name')->find();
            $list[$k]['name'] = $house['name'];
            $list[$k]['bd_name'] = Db::name('wy_bd_info')->where('id','=',$house['bd_info_id'])->value('name');
            $list[$k]['build_name'] = Db::name('wy_building')->where('id','=',$house['building_id'])->value('name');
            $list[$k]['unit_name'] = Db::name('wy_unit')->where('id','=',$house['unit_id'])->value('name');
            $list[$k]['type_txt'] = $it[$v['type']];
        }
        return __success('ok',['data'=>$list]);
    }

    // 获取小区楼宇单元房屋列表
    public function getCommunityBuildingUnitHouse(){
        $param = $this->request->param();
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        // if(@$param['cm_mg_id']){
        //     $where[] = ['id','in',$param['cm_mg_id']];
        // }
        if($this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $communityList = Db::name('wy_bd_info')->where($where)->field('id value,name label')->select();
        $communityIds = array();
        foreach ($communityList as $key=>$value) array_push($communityIds,$value['value']);
        // 楼宇
        $buildingList = Db::name('wy_building')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id,status')->select();
        $buildingIds = array();
        foreach ($buildingList as $key=>$value) array_push($buildingIds,$value['value']);
        // 单元
        $unitList = Db::name('wy_unit')->where('building_id','in',$buildingIds)->where(['is_deleted'=>0])->field('id value,name label,building_id')->select();
        $unitIds = array();
        foreach ($unitList as $key=>$value) array_push($unitIds,$value['value']);
        // 房屋
        $housesList = Db::name('wy_houses')->where('unit_id','in',$unitIds)->where(['is_deleted'=>0])->field('id value,name label,unit_id')->select();
        // 拼装数据
        $allData = array();
        foreach ($communityList as $ck=>$cv){
            $cv['children'] = array();
            $cv['title']=$cv['label'];
            $cv['key']=$cv['value'];
            foreach ($buildingList as $bk=>$bv){
                switch($bv['status']){
                    case 0:
                        $bv['label']=$bv['label'].'(禁用)';
                        break;
                    case 2:
                        $bv['label']=$bv['label'].'(拆除)';
                        break;
                    case 3:
                        $bv['label']=$bv['label'].'(出售)';
                        break;
                    case 4:
                        $bv['label']=$bv['label'].'(其它)';
                        break;
                }
                $bv['children'] = array();
                $bv['title']=$bv['label'];
                $bv['key']=$bv['value'];
                if($bv['bd_info_id'] === $cv['value']) {
                    unset($bv['bd_info_id']);
                    foreach ($unitList as $uk=>$uv){
                        $uv['children'] = array();
                        $uv['title']=$uv['label'];
                        $uv['key']=$uv['value'];
                        if($uv['building_id'] === $bv['value']) {
                            unset($uv['building_id']);
                            foreach ($housesList as $hk=>$hv){
                                $hv['title']=$hv['label'];
                                $hv['key']=$hv['value'];
                                if($hv['unit_id'] === $uv['value']){
                                    unset($hv['unit_id']);
                                    array_push($uv['children'],$hv);
                                }
                            }
                            array_push($bv['children'],$uv);
//                            if(!empty($uv['children'])) array_push($bv['children'],$uv);
                        }
                    }
                    array_push($cv['children'],$bv);
//                    if(!empty($bv['children'])) array_push($cv['children'],$bv);
                }
            }
            array_push($allData,$cv);
//            if(!empty($cv['children'])) array_push($allData,$cv);
        }
        return __success('ok',$allData);
    }

    // 根据type返回住户身份
    function getTypeText($type){
        if($type){
            return ['1'=>'业主本人','2'=>'亲属','3'=>'租客','4'=>'朋友','5'=>'同事','6'=>'保姆','7'=>'司机','8'=>'装修人员','9'=>'其它'][$type];
        }else {
            return '其它';
        }
    }
    // 返回住户身份
    function getHouseTypeText($type){
        return ['0'=>'住宅','1'=>'住宅','2'=>'公寓','3'=>'办公','4'=>'厂房','5'=>'仓库','6'=>'商铺','7'=>'酒店','8'=>'别墅','9'=>'其它'][$type];
    }
}